package cn.lg.soar.boot.client.api.token;

import cn.lg.soar.boot.client.api.exception.OverdueTokenException;
import cn.lg.soar.boot.client.api.exception.UnTokenException;
import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.client.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * API接口令牌提交拦截器
 * 
 * @author helios
 */
@Component
public class ClientTokenInterceptor extends HandlerInterceptorAdapter {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /** 用户信息服务 */
    @Autowired private ClientUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ClientToken annotation;
        
        // 对象是一个处理方法，则获取到方法上的注解
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod)handler).getMethodAnnotation(ClientToken.class);
        } else {
            return true;
        }
        
        // 方法没有FondleToken注解
        if (annotation == null) {
            return true;
        }
        
        // 从请求头获取token
        String token = request.getHeader("accesstoken");
        
        // 如果请求头没有token,则从请求参数中取
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("accesstoken");
        }

        // 如果还是没有token,则抛异常
        if (StringUtils.isBlank(token)) {
            throw new UnTokenException("请求必须携带令牌");
        }

        ClientUser user = userService.selectByToken(token);
        if (user == null) {
            logger.error("令牌信息不存在");
            throw new OverdueTokenException("令牌信息不存在");
        }else{
            if(!JWTUtil.getTokenInfo(token)) {
                logger.warn("\t用户token过期,请刷新token");
                throw new OverdueTokenException("用户token过期,请刷新token");
            }
        }
        
        return true;
    }

}
